package com.pms.api;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pms.controller.BaseController;
import com.pms.entity.Community;
import com.pms.exception.R;
import com.pms.service.ICommunityService;
import com.pms.service.IWaterPumpGroupAttrService;
import com.pms.service.IWaterPumpHouseService;
import com.pms.service.IWoGiaWpAttrService;
import com.pms.utils.LBSUtil;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ZPF
 * Created by hm on 2018/3/19.
 */
@RestController
@RequestMapping(value = "/pms/apiWaterPumpHomePage")
@Api(value="App地址水泵主页",description = "App地址水泵主页")
public class ApiWaterPumpHomePage extends BaseController {
    @Autowired
    IWaterPumpHouseService waterPumpHouseService;
    @Autowired
    IWaterPumpGroupAttrService waterPumpAttrService;
    @Autowired
    IWoGiaWpAttrService woGiaWpAttrService;
    @Autowired
    ICommunityService communityService;
    @Autowired
    private LBSUtil lBSUtil;

    /**
     * 水泵房地图选点
     * 暂时列表 及 数据选点 通用
     * @param communityId 小区ID
     * @return
     */
    @ApiOperation(value = "水泵房地图选点")
    @PostMapping(value = "/readWaterPumpHouseLbsByCommunity")
    @ApiImplicitParams({
            @ApiImplicitParam(name="wpHouseId",value="水泵房id",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="communityId",value="小区ID,和小区LbsID任意传1个",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="communityLbsPoiId",value="小区LbsID,和小区ID任意传1个",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="radius",value="lbs周边搜索范围,单位为m,默认值为1000",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageSize",value="查询数量，默认为10",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="查询页数，默认1页",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="resultType",value="返回结果类型(1-按水泵组区分数据，不分层| 默认-以水泵房区分数据，分层)",required = false,dataType = "int",paramType="form"),
    })
    public R readWaterPumpHouseLbsByCommunity(Long wpHouseId,Long communityId,String communityLbsPoiId,Integer radius,Integer pageSize,Integer pageNum,Integer resultType){
        if(communityId==null && StringUtils.isBlank(communityLbsPoiId)){
            return  R.error(400,"请求参数不能为空");
        }
        if(radius==null|| radius<=0){
            radius =1000;//默认查询1000米范围
        }
        if(pageNum==null|| pageNum<1){
            pageNum =1;//默认查询10条数据
        }
        if(pageSize==null|| pageSize<=0){
            pageSize =10;//默认查询10条数据
        }
        Wrapper<Community> wp = new EntityWrapper<Community>();
        if(communityId!=null){
            wp.eq("community_id",communityId);
        }
        if(StringUtils.isNotBlank(communityLbsPoiId)){
            wp.eq("lbs_poi_id",communityLbsPoiId);
        }
        Community community = communityService.selectOne(wp);
        if(community==null){
            return R.error(400,"未查询到小区信息");
        }
        if(StringUtils.isBlank(community.getLbsPoiId())|| community.getLongitude()==null|| community.getLatitude()==null){
            return R.error(400,"小区地图信息未完善，请联系相关人员");
        }
        Map<String, Object> lbsParamMap = new HashMap<String, Object>();
        lbsParamMap.put("ak", lBSUtil.getAK());
        lbsParamMap.put("geotable_id", lBSUtil.getWaterPumpHouseGeotableId());
        lbsParamMap.put("location", community.getLongitude()+","+community.getLatitude());
        lbsParamMap.put("coord_type", 3);//坐标类型
        lbsParamMap.put("radius",radius);
        lbsParamMap.put("page_index",pageNum-1);
        lbsParamMap.put("page_size",pageSize);
        StringBuffer filterStr =new StringBuffer("communityId:"+community.getCommunityId()+"|communityPoiId:"+community.getLbsPoiId());
        if(wpHouseId!=null){
            filterStr.append("|houseId:"+wpHouseId);
        }
        lbsParamMap.put("filter", filterStr.toString());//poi名称
        JSONObject lbsJson = LBSUtil.poiGeoSearchByMap(lbsParamMap);
        String status = lbsJson.getString("status");
        Assert.parameterIsBlank(status, "请求参数格式错误");
        if (!status.equals("0")) {
            return R.error("请求参数格式错误");
        }
        List<Map<String,Object>> returnList = new ArrayList<Map<String,Object>>();
        JSONArray poiContentsArray = lbsJson.getJSONArray("contents");
        if (null != poiContentsArray && !poiContentsArray.isEmpty()) {
            for (int x = 0, len = poiContentsArray.size(); x < len; x++) {
                JSONObject poiContentJson = (JSONObject) poiContentsArray.get(x);
                String poiId = poiContentJson.getString("uid");//获取到水泵房id
                if(resultType!=null&&resultType==1){
                    List<Map<String,Object>> result = waterPumpHouseService.readWaterPumpHouseOutlineHouseList(null,poiId,null);
                    if(result!=null&&!result.isEmpty()){
                        for(int z=0,length=result.size();z<length;z++){
                            String groupNameStr = result.get(z).get("groupName").toString();
                            if(groupNameStr.startsWith("WOGIA")){
                                result.get(z).putAll(woGiaWpAttrService.selectNewOneAttrByTablenameAndColumn(groupNameStr));
                            }
                        }
                        returnList.addAll(result);
                    }
                    //pressureFeedback count SZGWYL  waterFrequency
                }else{
                    Map<String,Object> result =waterPumpHouseService.readWaterPumpHouseoutline(null,poiId);
                    if(result!=null){

                      List<Map<String,Object>> groupListArray= ( List<Map<String,Object>>)result.get("groupList");
                        for(int z=0,length=groupListArray.size();z<length;z++){
                            String groupNameStr = groupListArray.get(z).get("groupName").toString();
                            if(groupNameStr.startsWith("WOGIA")){
                                groupListArray.get(z).putAll(woGiaWpAttrService.selectNewOneAttrByTablenameAndColumn(groupNameStr));
                            }
                        }
                        returnList.add(result);
                    }
                }
            }
        }
        return  R.ok().put("data",returnList);
    }


    /**
     * 根据小区ID查询水务主页
     * 考虑 lbs 及 数据库验证问题，暂不使用
     * @param communityId 小区ID
     * @return
     */
    @ApiOperation(value = "水泵房列表查询-暂不使用")
    @PostMapping(value = "/readWaterPumpHouseListByCommunity")
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="小区ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="resultType",value="返回结果类型(1-按水泵组区分数据，不分层| 默认-以水泵房区分数据，分层)",required = false,dataType = "int",paramType="form"),

    })
    public R readWaterPumpHouseListByCommunity(Long communityId,Integer resultType){
        parameterIsNull(communityId,"小区ID不能为空");
        List<Map<String,Object>> returnList = null;
        if(resultType!=null&&resultType==1){
            returnList =waterPumpHouseService.readWaterPumpHouseOutlineHouseList(null,null,communityId);
        }else{
            returnList =waterPumpHouseService.readWaterPumpHouseoutline(communityId);
        }
        if(returnList==null){
            returnList = new ArrayList<Map<String,Object>>();
        }
        return  R.ok().put("data",returnList);
    }

}
